<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of sms
 *
 * @author win7
 */
class sms {

    var $username;
    var $password;
    var $sms_option;

    public function __construct() {
       
        $this->username = $this->get_option('sms_username');
        $this->password =  $this->get_option('sms_password');
    }
    function get_option($code = false) {
    	 $CI = &get_instance();
    	$CI->db->select('value');
    	$sql = $CI->db->get_where('settings', array('code' => $code));
    	$row = $sql->row();
    	return $row->value;
    }
//////////////////////////////////////////////////////
//   Convert Characters, work as url encoder.
//   Note:Our system will decode this format only.
//////////////////////////////////////////////////////
    public function UrlEncoding($str) {
        $strResult = "";
        for ($i = 0; $i <= strlen($str); $i++) {
            $strResult .= (ord(substr($str, $i, 1))) . "+";
        }
        return $strResult;
    }

//////////////////////////////////////////////////////
//   Get  SMS Credits
//////////////////////////////////////////////////////
    public function GetCredits($UserName, $UserPassword) {
        @$url = "http://saudisms.net/gw/Balance.php?userName=" . $UserName . "&userPassword=" . $UserPassword;
        if (!(@$fp = fopen($url, "r"))) {
            $FainalResult = "Erorr Connecting to Gateway.";
        } else {
            @$FainalResult = @fread(@$fp, 50);
            @fclose(@$fp);
            @$FainalResult = (integer) str_replace(" ", "", @$FainalResult);
        }
        return $FainalResult;
    }

//////////////////////////////////////////////////////
//   Send SMS Messages
//////////////////////////////////////////////////////
    public function SendSms($UserName, $UserPassword, $Numbers, $Originator, $Message) {
        $url = "http://saudisms.net/gw/?userName=" . $UserName . "&userPassword=" . $UserPassword . "&numbers=" . $Numbers . "&userSender=" . $Originator . "&msg=" . $Message . "&By=MTJAR";
        if (!(@$fp = fopen($url, "r"))) {
            return "Erorr Connecting to Gateway.";
        } else {
            @$FainalResult = @fread(@$fp, 10);
            @fclose(@$fp);
            @$FainalResult = (integer) str_replace(" ", "", @$FainalResult);
            return $FainalResult;
            /*if ($FainalResult == "1") {
                return "SMS Sent Successfully.";
            } elseif ($FainalResult == "1010") {
                return "Missing Data, Message content or Numbers.";
            } elseif ($FainalResult == "1020") {
                return "Wrong Login Combination.";
            } elseif ($FainalResult == "1030") {
                return "Same message with same destinations exist in queue, Wait 10 seconds befoure resending it.";
            } elseif ($FainalResult == "1040") {
                return "Unrecognized Charset.";
            } elseif ($FainalResult == "1050") {
                return "Msg Empty. Reason, message fileration remove message content.";
            } elseif ($FainalResult == "1060") {
                return "Insufficient Credits to procces sending.";
            } elseif ($FainalResult == "1070") {
                return "Your Credits is 0, Insufficient to procces sending.";
            } elseif ($FainalResult == "1080") {
                return "Message Not Sent, Error Sending Message.";
            } elseif ($FainalResult == "1090") {
                return "Repetition filter catch the message.";
            } elseif ($FainalResult == "1100") {
                return "Sorry, Message Not Sent. Try later.";
            } elseif ($FainalResult == "1110") {
                return "Sorry, Bad Originator (Sender Name) you used. Try another Originator.";
            } elseif ($FainalResult == "1120") {
                return "Sorry,The country you are trying to send to is not covered by our network.";
            } elseif ($FainalResult == "1130") {
                return "Sorry, Consult our network administrator regarding defiend netowrk for you account.";
            } elseif ($FainalResult == "1140") {
                return "Sorry, You exceeded maximum messages parts. Try sending fewer parts.";
            } else {
                return $FainalResult;
            }*/
        }
    }

/////////////////////// End Of Functions ///////////////////////

    public function send_sms($number, $sender_name, $message) {
        $UserName = $this->UrlEncoding($this->username);
// Your password
        $UserPassword = $this->UrlEncoding($this->password);
// Destnation Numbers seprated by comma if more than one and no more than 120 numbers Per time.
        $Numbers = $this->UrlEncoding($number);
// Originator Or Sender name. In English no more than 11 Numbers or Characters or Both
        $Originator = $this->UrlEncoding($sender_name);
// Your Message in English or arabic or both.
// Each 70 Arabic Characters will be charged 1 Credit, Each 160 English Characters will be charged 1 Credit.
        $Message = $this->UrlEncoding($message);
// Storing Sending result in a Variable.
        return $SendingResult = $this->SendSms($UserName, $UserPassword, $Numbers, $Originator, $Message);
    }

    /**
     * get your blance
     */
    public function get_blance() {
        // Your username
        $UserName = $this->UrlEncoding($this->username);
// Your password
        $UserPassword = $this->UrlEncoding($this->password);
// Storing your credits in a Variable.
        return $this->GetCredits($UserName, $UserPassword);
    }

    /**
     * get user sms balance 
     * @param type $user_id
     * @return int 
     */
    public function get_user_sms_balance($user_id) {
        $CI = &get_instance();
        $CI->db->limit(1);
        $sql = $CI->db->get_where('users_balance', array('user_id' => $user_id, 'title' => 'sms'));
        if ($sql->num_rows()) {
            $row = $sql->row();
            return $row->value;
        } else {
            return 0;
        }
    }

    public function add_balance($num_msg = 1, $user_id) {
        $CI = &get_instance();

        $balance = $num_msg;
        // add balance

        if (is_found_balance('sms', $user_id)) {
            // increment
            $this->db->where('user_id', $user_id);
            $this->db->where('title', 'sms');
            $this->db->set('value', 'value+' . $balance, FALSE);
            $this->db->update('users_balance');
        } else {
            //insert new
            $CI->db->insert('users_balance', array('user_id' => $user_id, 'title' => 'sms', 'value' => $balance, 'create_date' => date('Y-m-d H:i:s')));
        }
    }

    /**
     * 
     * @param type $data
     * @return boolean
     */
    public function insert_msg($data = array()) {
        $CI = &get_instance();
        
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['type'] = 'wait';
        $data['mobile'] = $this->mobile_each_filter($data['mobile']);
        $data['point'] = $this->get_point($data['mobile'], $data['message']);
        $data['message_cost'] = $this->get_msg_cost($data['point'], $data['user_id']);
        $data['user_message_cost'] = $this->get_user_message_cost($data['user_id']);
        $data['message_part'] = $this->get_msg_part($data['message']);


        if ($this->get_user_sms_balance($data['user_id']) >= $data['point']) {
            $CI->db->insert('sms_send', $data);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 
     * @param type $mobile
     * @param type $limit
     * @param type $key_country
     * @return type
     */
    /* public function filter_mobile($mobile, $limit = 12, $key_country = '966') {
      $mobile_linit = strlen($mobile);
      $mobile_filter = $mobile;

      if ($mobile_linit == $limit) {
      $mobile_filter = $mobile;
      } elseif ($mobile_linit > $limit) {
      $substr = $mobile_linit - 9;
      //$substr=substr($mobile,0,$substr) ;

      $mobile_filter = substr_replace($mobile, $key_country, 0, $substr);
      } elseif ($mobile_linit < $limit && $mobile_linit == 9) {
      $mobile_filter = $key_country . $mobile;
      } elseif ($mobile_linit < $limit && $mobile_linit == 10) {


      $mobile_filter = substr_replace($mobile, $key_country, 0, 1);
      } elseif ($mobile_linit < $limit && $mobile_linit > 10) {
      $substr = $mobile_linit - 9;
      $mobile_filter = substr_replace($mobile, $key_country, 0, $substr);
      }


      return $mobile_filter;
      }
     */

    public function mobile_each_filter($mobile,$delimiter = ','){
    	$explode=explode($delimiter,$mobile);
    	$explode=array_filter($explode);
    	$resulr='';
    	foreach ($explode as $val){
    		$resulr.= $this->mobile_filter($val).',';
    	}
    	return rtrim($resulr,',');
    	
    }
    public function mobile_filter($mobile, $limit = 12,$min=9, $key_country = '966') {
        $strlrn = strlen($mobile);
		
        if ($strlrn == ($min+1) && substr($mobile, 0, 1) == 0) {
            $mobile = $key_country . substr($mobile, 1, $min);
        } elseif ($strlrn == $limit && substr($mobile, 0, 3) == $key_country) {
            $mobile = $mobile;
        } elseif ($strlrn > $min) {
            $limit = ($strlrn - $min);
            $mobile = $key_country . substr($mobile, $limit, $min);
        }

        return $mobile;
    }

    /**
     * 
     * @param type $point
     * @param type $user_id
     * @return type
     */
    public function get_msg_cost($point = 1, $user_id) {

        $user_message_cost = $this->get_user_message_cost($user_id);
        return $point * $user_message_cost;
    }

    /**
     * 
     * @param type $user_id
     * @return int
     */
    public function get_user_message_cost($user_id) {
        return 10;
    }

    /**
     * 
     * @param type $mobiles
     * @param type $message
     * @return int
     */
    public function get_point($mobiles, $message) {
        // get number length
        $mobiles_length = $this->get_mobile_length($mobiles);
        // get msg part
        $msg_part = $this->get_msg_part($message);
        // return number length * msg part
        return ($mobiles_length * $msg_part);
    }

    /**
     * 
     * @param type $msg
     * @return int
     */
    public function get_msg_part($msg) {
        // get type if arabic or english
        //arabic 70 word eng 160
        if (preg_match('/^[a-z0-9.-_]+$/', $msg)){ // '/[^a-z\d]/i' should also work.
            // lang = english 160
            $division = 160;
        } else {
            // lang = arabic  70
            $division = 70;
        }

        // part = message length/160 or 70
        $parts = strlen($msg) / $division;
        return ceil($parts);
    }

    /**
     * 
     * @param type $mobile
     * @param type $delimiter
     * @return type
     */
    public function get_mobile_length($mobile, $delimiter = ',') {
        $explod = explode($delimiter, $mobile);
        $mobile_length = array_filter($explod);
        return count($mobile_length);
    }

}

?>
